from django.shortcuts import render
from django.db import models
from rest_framework.pagination import PageNumberPagination

# Create your views here.
from shopping.models import Product, BrowsingRecord, FavoriteRecord, OrderRecord, CartRecord, ProductDetail
from rest_framework import viewsets
from .serializers import ProductSerializer, BrowsingRecordSerializer, FavoriteRecordSerializer, OrderRecordSerializer, \
    CartRecordSerializer
from rest_framework.views import APIView
from rest_framework.response import Response
from rest_framework import status
from utils.redis_client import get_redis_client
import json
from time import sleep
import threading
import pandas as pd
import numpy as np
from sklearn.metrics.pairwise import cosine_similarity
from langchain.agents import tool
from langchain.agents import initialize_agent, Tool
from langchain.agents import AgentType
from langchain_community.llms.tongyi import Tongyi
from django.http import JsonResponse
import os
import time
from rest_framework.permissions import AllowAny
from django.views.decorators.csrf import csrf_exempt
from django.utils.decorators import method_decorator
from django.http import HttpResponse
from django.db import transaction
from django.conf import settings
from django.utils import timezone
from datetime import timedelta
import uuid
from .models import OrderRecord, ProductDetail, Product
from utils.alipaysdk import AliPaySDK, get_alipay_client


class ShopPagination(PageNumberPagination):
    page_size = 10
    page_size_query_param = 'page_size'


class ProductViewSet(viewsets.ReadOnlyModelViewSet):
    queryset = Product.objects.all().order_by('order', '-id')
    serializer_class = ProductSerializer
    pagination_class = ShopPagination


# 延时双删函数
def delayed_delete_newslist():
    r = get_redis_client()
    import time
    time.sleep(0.5)
    r.delete('newslist')


class BrowsingRecordView(APIView):
    def post(self, request):
        user_id = request.data.get('userid')
        product_id = request.data.get('goodsid')
        if not user_id or not product_id:
            return Response({'code': 400, 'msg': '参数缺失'}, status=status.HTTP_400_BAD_REQUEST)
        record, created = BrowsingRecord.objects.get_or_create(user_id=user_id, product_id=product_id)
        from django.utils import timezone
        record.quantity += 1 if not created else 1
        record.timestamp = timezone.now()  # 每次浏览都更新时间
        record.save()
        # 延时双删缓存
        r = get_redis_client()
        r.delete('newslist')
        threading.Thread(target=delayed_delete_newslist).start()
        return Response({'code': 200, 'msg': '浏览记录已更新', 'id': record.id, 'quantity': record.quantity})


class FavoriteRecordView(APIView):
    def post(self, request):
        user_id = request.data.get('userid')
        product_id = request.data.get('goodsid')
        if not user_id or not product_id:
            return Response({'code': 400, 'msg': '参数缺失'}, status=status.HTTP_400_BAD_REQUEST)
        record, created = FavoriteRecord.objects.get_or_create(user_id=user_id, product_id=product_id)
        if not record.is_favorited:
            record.is_favorited = True
            record.timestamp = timezone.now()  # 关键：每次重新收藏都更新时间
            record.save()
        else:
            record.is_favorited = not record.is_favorited
            record.save()
            msg = '已取消收藏' if not record.is_favorited else '已收藏'
        # 延时双删缓存
        r = get_redis_client()
        r.delete('newslist')
        threading.Thread(target=delayed_delete_newslist).start()
        return Response({'code': 200, 'msg': msg, 'id': record.id, 'is_favorited': record.is_favorited})


class FavoriteListView(APIView):
    def get(self, request):
        user_id = request.query_params.get('userid')
        page = int(request.query_params.get('page', 1))
        page_size = int(request.query_params.get('page_size', 10))
        if not user_id:
            return Response({'code': 400, 'msg': '参数缺失'}, status=status.HTTP_400_BAD_REQUEST)
        qs = FavoriteRecord.objects.filter(user_id=user_id, is_favorited=True).select_related('product').order_by(
            '-timestamp')
        total = qs.count()
        start = (page - 1) * page_size
        end = start + page_size
        records = qs[start:end]
        data = [
            {
                'id': r.id,
                'product': ProductSerializer(r.product).data,
                'timestamp': r.timestamp
            } for r in records
        ]
        return Response({'code': 200, 'favorites': data, 'total': total})


class OrderRecordView(APIView):
    def post(self, request):
        user_id = request.data.get('userid')
        product_id = request.data.get('goodsid')
        quantity = int(request.data.get('quantity', 1))
        if not user_id or not product_id:
            return Response({'code': 400, 'msg': '参数缺失'}, status=status.HTTP_400_BAD_REQUEST)
        try:
            product = Product.objects.get(id=product_id)
        except Product.DoesNotExist:
            return Response({'code': 404, 'msg': '商品不存在'}, status=status.HTTP_404_NOT_FOUND)
        # 检查商品详情是否存在
        if not hasattr(product, 'detail') or product.detail is None:
            return Response({'code': 400, 'msg': '商品详情不存在'}, status=status.HTTP_400_BAD_REQUEST)
        if product.detail.stock < quantity:
            return Response({'code': 400, 'msg': '库存不足'}, status=status.HTTP_400_BAD_REQUEST)
        # 扣减库存
        product.detail.stock -= quantity
        product.detail.save()
        order_no = str(uuid.uuid4()).replace('-', '')  # 32位唯一字符串
        record = OrderRecord.objects.create(
            user_id=user_id,
            product_id=product_id,
            quantity=quantity,
            order_no=order_no,  # 一定要传入
            status='pending'
        )
        # 延时双删缓存
        r = get_redis_client()
        r.delete('newslist')
        threading.Thread(target=delayed_delete_newslist).start()
        return Response({'code': 200, 'msg': '订单已生成', 'id': record.id, 'quantity': record.quantity})


class OrderListView(APIView):
    def get(self, request):
        user_id = request.query_params.get('userid')
        page = int(request.query_params.get('page', 1))
        page_size = int(request.query_params.get('page_size', 10))
        if not user_id:
            return Response({'code': 400, 'msg': '参数缺失'}, status=status.HTTP_400_BAD_REQUEST)
        qs = OrderRecord.objects.filter(user_id=user_id).select_related('product').order_by('-timestamp')
        total = qs.count()
        start = (page - 1) * page_size
        end = start + page_size
        records = qs[start:end]
        data = [
            {
                'id': r.id,
                'product': ProductSerializer(r.product).data,
                'quantity': r.quantity,
                'timestamp': r.timestamp
            } for r in records
        ]
        return Response({'code': 200, 'orders': data, 'total': total})


class BrowsingListView(APIView):
    def get(self, request):
        user_id = request.query_params.get('userid')
        page = int(request.query_params.get('page', 1))
        page_size = int(request.query_params.get('page_size', 10))
        if not user_id:
            return Response({'code': 400, 'msg': '参数缺失'}, status=status.HTTP_400_BAD_REQUEST)
        qs = BrowsingRecord.objects.filter(user_id=user_id).select_related('product').order_by('-timestamp')
        total = qs.count()
        start = (page - 1) * page_size
        end = start + page_size
        records = qs[start:end]
        data = [
            {
                'id': r.id,
                'product': ProductSerializer(r.product).data,
                'quantity': r.quantity,
                'timestamp': r.timestamp
            } for r in records
        ]
        return Response({'code': 200, 'browsings': data, 'total': total})


class HotProductListView(APIView):
    def get(self, request):
        page = int(request.query_params.get('page', 1))
        page_size = int(request.query_params.get('page_size', 8))
        r = get_redis_client()

        try:
            nlist = r.get('newslist')
        except Exception as e:
            logger.error(f"Redis读取失败: {e}")
            nlist = None

        if nlist:
            try:
                nlist = json.loads(nlist)
                total = len(nlist)
                start = (page - 1) * page_size
                end = start + page_size
                paged_nlist = nlist[start:end]
                return Response({"code": 200, "nlist": paged_nlist, "total": total})
            except Exception as e:
                logger.error(f"JSON解析失败: {e}")
                nlist = None  # 解析失败时继续执行后续逻辑

        # 使用相同的键名作为锁
        if r.setnx('newslist_lock', 1):
            try:
                # 设置锁的过期时间，防止死锁
                r.expire('newslist_lock', 60)

                # 统计三表
                # 浏览
                browse = BrowsingRecord.objects.values('product').annotate(cnt=models.Sum('quantity'))
                browse_dict = {b['product']: b['cnt'] for b in browse}
                # 收藏
                fav = FavoriteRecord.objects.filter(is_favorited=True).values('product').annotate(
                    cnt=models.Count('id'))
                fav_dict = {f['product']: f['cnt'] for f in fav}
                # 订单
                order = OrderRecord.objects.values('product').annotate(cnt=models.Sum('quantity'))
                order_dict = {o['product']: o['cnt'] for o in order}

                print('browse_dict:', browse_dict)
                print('fav_dict:', fav_dict)
                print('order_dict:', order_dict)

                # 计算权重分
                score = {}
                for pid in set(list(browse_dict) + list(fav_dict) + list(order_dict)):
                    s = (order_dict.get(pid, 0) * 0.3 + fav_dict.get(pid, 0) * 0.3 + browse_dict.get(pid, 0) * 0.4)
                    score[pid] = s

                print('score:', score)

                # 排序取前30
                top = sorted(score.items(), key=lambda x: x[1], reverse=True)[:30]
                print('top:', top)

                # 查询商品信息
                products = Product.objects.in_bulk([pid for pid, _ in top])
                print('products:', products)
                nlist = [ProductSerializer(products[pid]).data for pid, _ in top if pid in products]
                print('nlist:', nlist)

                # 序列化并存储到Redis
                r.set('newslist', json.dumps(nlist), ex=3600)

                total = len(nlist)
                start = (page - 1) * page_size
                end = start + page_size
                paged_nlist = nlist[start:end]
                return Response({"code": 200, "nlist": paged_nlist, "total": total})
            except Exception as e:
                logger.error(f"数据处理或缓存设置失败: {e}")
                # 发生异常时返回空列表或错误信息
                return Response({"code": 500, "message": "获取热门商品失败", "nlist": [], "total": 0})
            finally:
                # 确保锁被释放
                r.delete('newslist_lock')
        else:
            # 获取锁失败，等待重试
            try:
                # 使用更短的等待时间和重试机制
                for i in range(3):
                    sleep(0.5)
                    nlist = r.get('newslist')
                    if nlist:
                        nlist = json.loads(nlist)
                        total = len(nlist)
                        start = (page - 1) * page_size
                        end = start + page_size
                        paged_nlist = nlist[start:end]
                        return Response({"code": 200, "nlist": paged_nlist, "total": total})
                # 重试多次后仍然没有数据
                return Response({"code": 200, "nlist": [], "total": 0})
            except Exception as e:
                logger.error(f"等待缓存时出错: {e}")
                return Response({"code": 500, "message": "获取热门商品失败", "nlist": [], "total": 0})


llm = Tongyi()
DATA_FILE = "user_goods_data.csv"
SIMILARITY_CACHE = "user_similarity.json"


@tool
def collect_goods(input: str) -> str:
    """
    当用户浏览或购买了商品后，记录用户行为数据
    输入格式：用户id,商品id,数量,行为类型(浏览/购买)
    例如：1001,2003,1,购买
    """
    try:
        user_id, goods_id, count, action = input.split(',')
        if not os.path.exists(DATA_FILE):
            df = pd.DataFrame(columns=['userid', 'goodsid', 'count', 'action'])
            df.to_csv(DATA_FILE, index=False)
        new_data = pd.DataFrame({
            'userid': [user_id],
            'goodsid': [goods_id],
            'count': [count],
            'action': [action]
        })
        new_data.to_csv(DATA_FILE, mode='a', header=False, index=False)
        return f"成功记录用户{user_id}对商品{goods_id}的{action}行为，数量{count}"
    except Exception as e:
        return f"数据收集失败: {str(e)}。请使用格式：用户id,商品id,数量,行为类型"


@tool
def similarity(input: str) -> str:
    """
    分析用户相似度，获取最相似的前10个用户
    输入格式：目标用户id
    例如：1001
    """
    try:
        user_id = input.strip()
        if not os.path.exists(DATA_FILE):
            return "暂无用户行为数据，无法计算相似度"
        df = pd.read_csv(DATA_FILE)
        df['weight'] = df['action'].map({'购买': 6, '浏览': 4}).fillna(1)
        user_item_matrix = df.pivot_table(
            index='userid',
            columns='goodsid',
            values='weight',
            aggfunc='sum',
            fill_value=0
        )
        similarity_matrix = cosine_similarity(user_item_matrix)
        np.fill_diagonal(similarity_matrix, 0)
        if int(user_id) not in user_item_matrix.index:
            return f"用户{user_id}不存在于数据中"
        user_idx = user_item_matrix.index.get_loc(int(user_id))
        similar_indices = np.argsort(similarity_matrix[user_idx])[::-1][:10]
        similar_users = user_item_matrix.index[similar_indices].tolist()
        similarity_scores = similarity_matrix[user_idx][similar_indices].tolist()
        similarity_data = {
            user_id: {
                'similar_users': similar_users,
                'scores': similarity_scores,
                'timestamp': int(time.time())
            }
        }
        with open(SIMILARITY_CACHE, 'w') as f:
            json.dump(similarity_data, f)
        result = [f"用户{similar_users[i]}: 相似度{similarity_scores[i]:.4f}" for i in range(len(similar_users))]
        return f"与用户{user_id}最相似的10个用户：\n" + "\n".join(result)
    except Exception as e:
        return f"相似度计算失败: {str(e)}"


@tool
def recommend_product(input: str) -> str:
    """
    基于用户相似度为用户推荐商品
    输入格式：目标用户id,推荐数量(可选，默认为5)
    例如：1001,8
    """
    try:
        params = input.split(',')
        user_id = params[0].strip()
        num_recommendations = int(params[1].strip()) if len(params) > 1 else 5
        if not os.path.exists(SIMILARITY_CACHE):
            return "请先计算用户相似度"
        with open(SIMILARITY_CACHE, 'r') as f:
            similarity_data = json.load(f)
        if user_id not in similarity_data:
            return f"没有用户{user_id}的相似度数据，请先计算"
        similar_users = similarity_data[user_id]['similar_users']
        if not os.path.exists(DATA_FILE):
            return "暂无用户行为数据，无法生成推荐"
        df = pd.read_csv(DATA_FILE)
        user_items = set(df[df['userid'] == int(user_id)]['goodsid'].tolist())
        recommendations = {}
        for similar_user in similar_users:
            similar_user_items = df[df['userid'] == int(similar_user)]
            for _, item in similar_user_items.iterrows():
                if item['goodsid'] not in user_items:
                    similarity_score = next(
                        score for idx, score in enumerate(similarity_data[user_id]['scores'])
                        if similar_users[idx] == similar_user
                    )
                    action_weight = 5 if item['action'] == '购买' else 1
                    recommendation_score = similarity_score * action_weight * item['count']
                    if item['goodsid'] in recommendations:
                        recommendations[item['goodsid']] += recommendation_score
                    else:
                        recommendations[item['goodsid']] = recommendation_score
        sorted_recommendations = sorted(recommendations.items(), key=lambda x: x[1], reverse=True)
        product_info = {
            'g001': "夏季连衣裙",
            'g002': "男士T恤",
            'g003': "运动鞋"
        }
        result = []
        for goods_id, score in sorted_recommendations[:num_recommendations]:
            product_name = product_info.get(goods_id, f"商品{goods_id}")
            result.append(f"{product_name} (商品ID: {goods_id}, 推荐分数: {score:.2f})")
        return f"为用户{user_id}推荐的商品：\n" + "\n".join(result)
    except Exception as e:
        return f"商品推荐失败: {str(e)}"


class Recommend(APIView):
    def get(self, request):
        tools = [
            Tool(
                name="collect_goods",
                func=collect_goods,
                description="当用户浏览或购买了商品后，记录用户行为数据。输入格式：用户id,商品id,数量,行为类型(浏览/购买)，例如：1001,2003,1,购买"
            ),
            Tool(
                name="similarity",
                func=similarity,
                description="分析用户相似度，获取最相似的前10个用户。输入格式：目标用户id，例如：1001"
            ),
            Tool(
                name="recommend_product",
                func=recommend_product,
                description="基于用户相似度为用户推荐商品。输入格式：目标用户id,推荐数量(可选，默认为5)，例如：1001,8"
            )
        ]
        agent = initialize_agent(
            tools,
            llm,
            agent=AgentType.ZERO_SHOT_REACT_DESCRIPTION,
            verbose=True
        )
        try:
            action = request.GET.get('action')
            userid = request.GET.get('userid')
            if not action or not userid:
                return JsonResponse({"code": 400, "error": "缺少必要参数"})
            if action == 'collect':
                goodsid = request.GET.get('goodsid')
                count = request.GET.get('count', 1)
                action_type = request.GET.get('action_type', '浏览')
                input_str = f"{userid},{goodsid},{count},{action_type}"
                res = agent.invoke(input_str)
            elif action == 'similarity':
                num = 10
                input_str = f"{userid},{num}"
                res = agent.invoke(input_str)
            elif action == 'recommend':
                num = request.GET.get('num', 5)
                input_str = f"{userid},{num}"
                res = agent.invoke(input_str)
            else:
                return JsonResponse({"code": 400, "error": "未知操作类型"})
            return JsonResponse({"code": 200, "data": res})
        except Exception as e:
            return JsonResponse({"code": 500, "error": str(e)})


class CartRecordView(APIView):
    permission_classes = [AllowAny]

    def get(self, request):
        user_id = request.query_params.get('userid')
        if not user_id:
            return Response({'code': 400, 'msg': '参数缺失'}, status=status.HTTP_400_BAD_REQUEST)
        qs = CartRecord.objects.filter(user_id=user_id, checked_out=False).select_related('product').order_by(
            '-timestamp')
        data = CartRecordSerializer(qs, many=True).data
        return Response({'code': 200, 'carts': data})

    def post(self, request):
        user_id = request.data.get('userid')
        product_id = request.data.get('goodsid')
        quantity = int(request.data.get('quantity', 1))
        if not user_id or not product_id:
            return Response({'code': 400, 'msg': '参数缺失'}, status=status.HTTP_400_BAD_REQUEST)
        # 若购物车已存在该商品则数量累加
        record, created = CartRecord.objects.get_or_create(user_id=user_id, product_id=product_id, checked_out=False)
        if not created:
            record.quantity += quantity
            record.save()
        else:
            record.quantity = quantity
            record.save()
        return Response({'code': 200, 'msg': '已加入购物车', 'id': record.id, 'quantity': record.quantity})

    def delete(self, request):
        cart_id = request.data.get('cartid')
        if not cart_id:
            return Response({'code': 400, 'msg': '参数缺失'}, status=status.HTTP_400_BAD_REQUEST)
        try:
            CartRecord.objects.filter(id=cart_id).delete()
            return Response({'code': 200, 'msg': '已移除'})
        except Exception as e:
            return Response({'code': 500, 'msg': str(e)})

    def patch(self, request):
        cart_id = request.data.get('cartid')
        quantity = request.data.get('quantity')
        if not cart_id or quantity is None:
            return Response({'code': 400, 'msg': '参数缺失'}, status=status.HTTP_400_BAD_REQUEST)
        try:
            record = CartRecord.objects.get(id=cart_id)
            record.quantity = int(quantity)
            record.save()
            return Response({'code': 200, 'msg': '数量已更新'})
        except CartRecord.DoesNotExist:
            return Response({'code': 404, 'msg': '购物车项不存在'})


class AlipayOrderView(APIView):
    def post(self, request):
        try:
            order_no = request.data.get('order_no')
            if order_no:
                # 幂等性：只用 order_no 查订单
                try:
                    order = OrderRecord.objects.get(order_no=order_no)
                except OrderRecord.DoesNotExist:
                    return Response({'code': 404, 'msg': '订单不存在'}, status=404)
                product_detail = ProductDetail.objects.get(product_id=order.product_id)
                price = str(product_detail.product.price)
                ali = AliPaySDK()
                pay_url = ali.page_pay(
                    out_trade_no=order_no,
                    total_amount=str(float(price) * order.quantity),
                    subject=f"购买商品: {product_detail.product.name}",
                    return_url=f"http://localhost:5173/order/success?order_no={order_no}"
                )
                return Response({'code': 0, 'pay_url': pay_url, 'order_no': order_no})

            # 新下单和幂等性校验
            userid = request.data.get('userid')
            goodsid = request.data.get('goodsid')
            quantity = int(request.data.get('quantity', 1))
            now = timezone.now()
            five_sec_ago = now - timedelta(seconds=5)

            # 幂等性校验：5秒内pending订单
            recent_order = OrderRecord.objects.filter(
                user_id=userid,
                product_id=goodsid,
                status='pending',
                timestamp__gte=five_sec_ago
            ).first()
            if recent_order:
                return Response({
                    'code': 3,
                    'msg': '5秒内已下单该商品，是否继续支付？',
                    'order_no': recent_order.order_no
                })

            # 检查库存
            with transaction.atomic():
                product_detail = ProductDetail.objects.select_for_update().get(product_id=goodsid)
                if product_detail.stock < quantity:
                    return Response({'code': 2, 'msg': '商品库存不足'}, status=400)
                price = str(product_detail.product.price)

                # 立即扣减库存
                product_detail.stock -= quantity
                product_detail.save()

                # 生成唯一订单号
                order_no = str(uuid.uuid4()).replace('-', '')

                # 写入订单表（pending）
                order = OrderRecord.objects.create(
                    user_id=userid,
                    product_id=goodsid,
                    quantity=quantity,
                    price=price,
                    order_no=order_no,
                    status='pending'
                )

                # 标记购物车商品为已结算（如果是从购物车支付的）
                CartRecord.objects.filter(
                    user_id=userid,
                    product_id=goodsid,
                    checked_out=False
                ).update(checked_out=True)

                # 生成支付链接
                ali = AliPaySDK()
                pay_url = ali.page_pay(
                    out_trade_no=order_no,
                    total_amount=str(float(price) * quantity),
                    subject=f"购买商品: {product_detail.product.name}",
                    return_url=f"http://localhost:5173/order/success?order_no={order_no}"
                )
                return Response({'code': 0, 'pay_url': pay_url, 'order_no': order_no})
        except Exception as e:
            import traceback
            print('支付宝下单接口异常:', traceback.format_exc())
            return Response({'code': 500, 'msg': f'后端异常: {str(e)}'}, status=500)


@method_decorator(csrf_exempt, name='dispatch')
class AlipayNotifyView(APIView):
    """
    支付宝异步回调处理
    幂等性：订单号已存在则直接返回success
    """

    def post(self, request):
        out_trade_no = request.data.get('out_trade_no')
        try:
            with transaction.atomic():
                # 查找对应的订单记录
                orders = OrderRecord.objects.filter(main_order_no=out_trade_no)
                if not orders.exists():
                    return HttpResponse("fail")
                for order in orders:
                    if order.status != 'paid':
                        # 扣减库存
                        product_detail = ProductDetail.objects.select_for_update().get(product_id=order.product_id)
                        if product_detail.stock < order.quantity:
                            return HttpResponse("fail")
                        product_detail.stock -= order.quantity
                        product_detail.save()
                        order.status = 'paid'
                        order.save()

            return HttpResponse("success")
        except Exception as e:
            print(f"支付宝回调处理异常: {e}")
            return HttpResponse("fail")


class CartPayView(APIView):
    def post(self, request):
        print("CartPayView 被调用")
        user_id = request.data.get('userid')
        items = request.data.get('items')  # [{goodsid: 1, quantity: 2}, ...]
        if not items:
            return Response({'code': 1, 'msg': '未选择商品'})
        total_amount = 0
        main_order_no = str(uuid.uuid4()).replace('-', '')
        try:
            with transaction.atomic():
                for item in items:
                    goodsid = item['goodsid']
                    quantity = item['quantity']
                    product_detail = ProductDetail.objects.select_for_update().get(product_id=goodsid)
                    if product_detail.stock < quantity:
                        return Response({'code': 2, 'msg': f'商品{goodsid}库存不足'})
                    total_amount += product_detail.product.price * quantity
                # 为每个商品写订单，全部写入 main_order_no
                for item in items:
                    goodsid = item['goodsid']
                    quantity = item['quantity']
                    order_no = str(uuid.uuid4()).replace('-', '')
                    OrderRecord.objects.create(
                        user_id=user_id,
                        product_id=goodsid,
                        quantity=quantity,
                        price=Product.objects.get(id=goodsid).price,
                        order_no=order_no,
                        main_order_no=main_order_no,
                        status='pending'
                    )
                    # 标记购物车
                    CartRecord.objects.filter(
                        user_id=user_id,
                        product_id=goodsid,
                        checked_out=False
                    ).update(checked_out=True)
                # 生成支付链接
                ali = AliPaySDK()
                pay_url = ali.page_pay(
                    out_trade_no=main_order_no,
                    total_amount=str(total_amount),
                    subject="购物车合并支付",
                    return_url=f"http://localhost:5173/order/success?order_no={main_order_no}"
                )
                print("支付宝支付链接：", pay_url)
                return Response({'code': 0, 'pay_url': pay_url, 'order_no': main_order_no})
        except Exception as e:
            print("CartPayView异常：", e)
            return Response({'code': 500, 'msg': str(e)})


class OrderDetailView(APIView):
    def get(self, request):
        order_no = request.GET.get('order_no', '').strip()
        if not order_no:
            return Response({'code': 1, 'msg': '缺少订单号'})

        # 1. 优先查批量订单（合并支付）
        orders = OrderRecord.objects.filter(main_order_no=order_no)
        if orders.exists():
            order_list = []
            for order in orders:
                product = Product.objects.get(id=order.product_id)
                order_list.append({
                    'order_no': order.order_no,
                    'product': ProductSerializer(product).data,
                    'quantity': order.quantity,
                    'price': str(order.price),
                    'status': order.status,
                    'timestamp': order.timestamp,
                })
            return Response({'code': 0, 'orders': order_list})

        # 2. 查单个订单（单品支付）
        order = OrderRecord.objects.filter(order_no=order_no).first()
        if order:
            product = Product.objects.get(id=order.product_id)
            return Response({
                'code': 0,
                'orders': [{
                    'order_no': order.order_no,
                    'product': ProductSerializer(product).data,
                    'quantity': order.quantity,
                    'price': str(order.price),
                    'status': order.status,
                    'timestamp': order.timestamp,
                }]
            })

        return Response({'code': 2, 'msg': '订单不存在或未支付成功'})